package easy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution_350 {
    public static int[] intersection(int[] nums1, int[] nums2) {

        Map<Integer, Integer> map1 = new HashMap<>();
        Map<Integer, Integer> map2 = new HashMap<>();
        for (int num : nums1) {
            Integer count1 = map1.getOrDefault(num, 0);
            map1.put(num, count1+1);
            map2.put(num, count1+1);
        }
        for (int num : nums2) {
            if (map2.containsKey(num)) {
                Integer count = map2.get(num);
                map2.put(num, count-1);
            }
        }
        List<Integer> list = new ArrayList<>();
        map1.forEach((key, val)->{
            int v2 = map2.get(key);
            if (val!=v2) {
                int length = v2 > 0 ? val - v2 : val;
                for (int i = 0; i < length; i++) {
                    list.add(key);
                }
            }
        });
        int[] r = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            r[i] = list.get(i);
        }
        return r;
    }

    public static void main(String[] args) {
        int[] intersection = intersection(new int[]{4,9,5}, new int[]{9,4,9,8,4});
        for (int i : intersection) {
            System.out.print(i+",");
        }
    }
}
